package com.markerhub.common.lang.exception;

import com.markerhub.common.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.ResultSet;

/**\
 *     //捕获全局异常
 *     @ControllerAdvice表示定义全局控制器异常处理，
 *     @ExceptionHandler表示针对性异常处理
 * {
 *     "msg": "success",
 *     "code": 500,
 *     "success": false,
 *     "message": "id不能为空！"
 * }
 * 抛异常后变成
 * {
 *     "timestamp": "2019-04-01T07:17:38.619+0000",
 *     "status": 500,
 *     "error": "Internal Server Error",
 *     "message": "id不能为空！",
 *     "path": "/api/myInfo"
 * }
 */
@Slf4j
@RestControllerAdvice //RestControllerAdvice(ControllerAdvice)拦截异常并统一处理  当我们定义了一个自定义返回参数格式时，希望得到统一的返回，如果在运行时发现了异常，也希望将异常统一返回

public class GlobalExceptionHandler {
    //shiro抛出的异常，比如没有权限，用户登录异常
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(value = ShiroException.class)
    public Result handler(ShiroException e){
        log.error("运行时异常：--------------{}",e);
        return Result.fail(401,e.getMessage(),null);
    }



    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e) {
        log.error("实体校验异常：--------------{}",e);
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return Result.fail(objectError.getDefaultMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e) {
        log.error("Assert异常：--------------{}",e);
        return Result.fail(e.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    public Result handler(RuntimeException e) {
        log.error("运行时异常：--------------{}",e);
        return Result.fail(e.getMessage());
    }


}
